#include "FormlessWidgetMoveBase.h"
#include <QtWidgets/QWidget>

#include <QtWidgets/QApplication>
#include <QScreen>
FormlessWidgetMoveBase::FormlessWidgetMoveBase()
	: m_bIsMove(false)
	, m_bCanMoveWithMouse(false), m_bIsUpdate(true) {
}

void FormlessWidgetMoveBase::onMousePressed(QWidget* widget, QMouseEvent* event) {
	if (canDragArea().contains(event->pos())
		&& widget
		&& checkMousePressedType(event)
		&& canMoveWithMouse()) {
		m_oriPos = widget->pos();
		m_beginPos = event->pos();
		m_point = event->globalPos();
	}
	else {
		m_beginPos = QPoint(-1, -1);
	}

}

void FormlessWidgetMoveBase::onMouseMoving(QWidget* widget, QMouseEvent* event) {
	if (canDragArea().contains(m_beginPos)
		&& widget
		&& canMoveWithMouse()
		&& (m_beginPos.x() != 0 || m_beginPos.y() != 0)) {
		setMoveState(true);
	}
	else {
		return;
	}

	QRect activeRect;
	activeRect.setTopLeft(QPoint(0, 0));

	if (widget->parentWidget() && !widget->windowFlags().testFlag(Qt::Dialog)) {
		activeRect.setSize(widget->parentWidget()->size());
	}
	else {
		QScreen* desktopWidget = QApplication::primaryScreen();//获取可用桌面大小
		if (desktopWidget) {
			activeRect.setSize(desktopWidget->availableGeometry().size());
		}
	}

	QPoint newPos = m_oriPos + (event->globalPos() - m_point);
	widget->move(newPos);
	if (m_bIsUpdate) {
		widget->update();
	}
	return;
	const int WOFFSET = 20;
	const int HOFFSET = 20;

	if (newPos.x() < activeRect.x() - widget->width() + WOFFSET) {
		newPos.setX(activeRect.x() - widget->width() + WOFFSET);
	}
	if (newPos.y() < activeRect.y()) {
		newPos.setY(activeRect.y());
	}
	if (newPos.x() > (activeRect.x() + activeRect.width() - WOFFSET)) {
		newPos.setX(activeRect.x() + activeRect.width() - WOFFSET);
	}
	if (newPos.y() > (activeRect.y() + activeRect.height() - HOFFSET)) {
		newPos.setY(activeRect.y() + activeRect.height() - HOFFSET);
	}

}

void FormlessWidgetMoveBase::onMouseRelease(QWidget* widget, QMouseEvent* event) {
	setMoveState(false);
	m_beginPos = QPoint(-1, -1);
}

bool FormlessWidgetMoveBase::checkMousePressedType(QMouseEvent* event) {
	return (event->button() == Qt::LeftButton
		&& event->modifiers() == Qt::NoModifier);
}
